package com.hunttown.mes.manage.controller._basic;

import com.hunttown.mes.manage.controller.common.AdminBaseClass;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.AnalysisCatalogManageService;
import com.hunttown.mes.rpc.domain.AnalysisVisualCatalogDTO;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.OperateCode;
import com.hunttown.mes.manage.service.AnalysisManageManageService;
import com.hunttown.mes.manage.service.WorkflowBusinessManageService;
import com.hunttown.mes.rpc.domain.AnalysisManageDTO;
import com.hunttown.mes.rpc.domain.WorkflowBusinessDTO;
import com.hunttown.mes.rpc.domain.enums.workflow.BusinessTypeEnum;
import com.hunttown.mes.rpc.domain.query.WorkflowBusinessDTOQuery;
import com.hunttown.mes.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.hunttown.mes.common.utils.PageUtils.PagePackage;

/**
 * @title: 流程业务
 * @author: wangjunfu
 * @date: 2019-08-01 16:55:14
 * @description:
 */
@Controller
@RequestMapping(value = "/basic/wfbusiness")
public class WFBusinessController {

    private final static Logger logger = LoggerFactory.getLogger(WFBusinessController.class);

    private final WorkflowBusinessManageService businessService;
    private final AnalysisManageManageService manageService;
    private final AnalysisCatalogManageService catalogService;
    private final ModelService modelService;

    @Autowired
    public WFBusinessController(WorkflowBusinessManageService businessService, AnalysisManageManageService manageService, AnalysisCatalogManageService catalogService, ModelService modelService) {
        this.businessService = businessService;
        this.manageService = manageService;
        this.catalogService = catalogService;
        this.modelService = modelService;
    }

    //region 数据列表

    /**
     * 首页
     *
     * @param model    model模型
     * @param dtoQuery 查询条件
     * @return vm
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model, WorkflowBusinessDTOQuery dtoQuery) {

        dtoQuery.setOrderBy("order by sort asc, id asc");
        Page<WorkflowBusinessDTO> dataPage = businessService.getForPage(dtoQuery);

        // 实时更新列表信息
        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (WorkflowBusinessDTO item : dataPage.getItems()) {
                //类别名称
                AnalysisVisualCatalogDTO catalog = catalogService.getFromCacheId(item.getCatalogId());
                if (catalog != null) {
                    item.setCatalogName(catalog.getCatalogName());
                    item.setCatalogNameEn(catalog.getCatalogNameEn());
                }
                item.setBusinessTypeName(BusinessTypeEnum.getEnumByKey(item.getBusinessType()));
            }
        }

        model.addAttribute("page", dataPage);
        model.addAttribute("PagePackage", PagePackage(dataPage.getPn(), dataPage.getStart(), dataPage.getPageSize(), dataPage.getTotalPages(), dataPage.getTotalItems()));
        model.addAttribute("dtoQuery", dtoQuery);

        return "basic/wfbusiness/index";
    }
    //endregion

    //region 编辑&保存

    /**
     * 编辑
     *
     * @param model model模型
     * @param id    主键id
     * @return json
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Integer id) {
        id = (id == null ? 0 : id);

        WorkflowBusinessDTO obj = new WorkflowBusinessDTO();
        obj.setId(id);
        obj.setBusinessType(1);
        obj.setSort(0);

        if (id > 0) {
            obj = businessService.getById(id);
        }
        model.addAttribute("Obj", obj);

        modelService.getCatalogPage(model, 19);

        return "basic/wfbusiness/edit";
    }

    /**
     * 保存 ajax异步
     *
     * @param request sevelet请求
     * @param objDTO  实体类
     * @return
     */
    @RequestMapping(value = "/saveEdit", method = RequestMethod.POST)
    @ResponseBody
    public String saveEditNotify(HttpServletRequest request, WorkflowBusinessDTO objDTO) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {

            //新增时检验是否唯一
            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                WorkflowBusinessDTOQuery query = new WorkflowBusinessDTOQuery();
                query.setBusinessNameEn(objDTO.getBusinessNameEn());
                WorkflowBusinessDTO obj = businessService.getByQuery(query);

                if (obj != null && obj.getId() > 0) {
                    map = OperateCode.CompositionResult(map, -10, "此流程代码已存在，请重新输入！");
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            if (objDTO.getId() == null || objDTO.getId() <= 0) {
                //新增
                //设置初始值
                String pin = AdminBaseClass.getPin(request);
                AnalysisManageDTO curr_obj = manageService.getFromCachePin(pin);
                objDTO.setAdminId(curr_obj.getId());
                objDTO.setCreateTime(new Date());
                objDTO.setStopFlag(0);
                objDTO.setDeleteFlag(0);
                objDTO = businessService.insert(objDTO);

                if (objDTO == null || objDTO.getId() <= 0) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }

            } else {
                //更新
                //将不需要更新的字段设置为NULL
                objDTO.setBusinessNameEn(null);
                Boolean isNext = businessService.updateInfoById(objDTO);

                if (!isNext) {
                    //操作失败
                    map = OperateCode.CompositionResult(map, -1);
                    result = JSONUtils.toJSON(map);
                    return result;
                }
            }

            //操作成功 结果返回
            map = OperateCode.CompositionResult(map, 1);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }
    //endregion

    //region 删除&改变状态

    /**
     * 通过id删除 ajax异步
     *
     * @param id 记录id
     * @return
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    @ResponseBody
    public String deleteNotify(Integer id) {

        // 结果返回结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        if (id == null || id <= 0) {
            map = OperateCode.CompositionResult(map, -10, "请选择要删除的记录！");
            result = JSONUtils.toJSON(map);
            return result;
        }

        try {
            Boolean isNext = businessService.delete(id);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    /**
     * 状态改变 ajax异步
     *
     * @param id     记录id
     * @param status 状态
     * @return
     */
    @RequestMapping(value = "/changeFlag", method = RequestMethod.POST)
    @ResponseBody
    public String openOrStopFlag(Integer id, Integer status) {

        // 结果返回 结果至少包含一个操作状态和一条状态信息
        String result = "";
        Map<String, String> map = new HashMap<String, String>();

        try {
            Boolean isNext = businessService.changeState(id, status);
            map = OperateCode.CompositionResult(map, isNext ? 1 : 0);
            result = JSONUtils.toJSON(map);
            return result;

        } catch (Exception e) {
            //清空map
            map.clear();
            map = OperateCode.CompositionResult(map, -1);
            result = JSONUtils.toJSON(map);
            return result;
        }
    }

    //endregion

}